package com.zhida.jiyangcenter.membership

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.manager.app
import chooongg.base.utils.startActivity
import chooongg.base.utils.tipFail
import chooongg.base.utils.tipWarn
import chooongg.base.utils.toast
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.mian.MainActivity
import com.zhida.jiyangcenter.order.PayTypeEntity
import com.zhida.jiyangcenter.utils.AliPay
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.SmoothCheckBox
import com.zhida.jiyangcenter.wxapi.WXPayEntryActivity
import kotlinx.android.synthetic.main.activity_pay_more_recharge.*


@TitleBar(false)
@ContentLayout(R.layout.activity_pay_more_recharge)
class PayMoreRechargeActivity : BaseActivity() {
    val adapter = Adapter()
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.title("充值").navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }
        rv_pay_order.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_pay_order.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context).sizeResId(R.dimen.dividerSmall)
                .colorResId(R.color.colorBack).build()
        )
        rv_pay_order.adapter = adapter
        adapter.setNewData(ArrayList<PayTypeEntity>().apply {
            add(PayTypeEntity(R.drawable.iv_pay_wechat, "微信支付", ""))
            add(PayTypeEntity(R.drawable.iv_pay_alipay, "支付宝支付", ""))
        })
        adapter.setOnItemClickListener { _, _, position ->
            adapter.position = position
            adapter.notifyDataSetChanged()
        }
        tv_pay_order.setOnClickListener {
            if (edit_phone.text.isNullOrEmpty()) {
                toast("请输入您的充值金额")
            } else
                when (adapter.position) {
                    -1 -> {
                        toast("请选择支付方式")
                    }
                    0 -> {
                        lifecycleScope.request({
                            APIMemberApps.service().recharg(edit_phone.text.toString().toInt())
                        }, object : BaseAPI<RechargeEntity>() {
                            override fun onSuccess(t: RechargeEntity?, state: Int, msg: String) {
                                lifecycleScope.request({
                                    APIPay.service().wxpay(
                                        t?.order_code ?: "",
                                        "6"
                                    )
                                }, object : BaseAPI<WechatEntity>() {
                                    override fun onSuccess(
                                        response: WechatEntity?,
                                        state: Int,
                                        msg: String
                                    ) {
                                        WXPayEntryActivity.setWxPay {
                                            for (i in app.activityStack.size - 1 downTo 0) {
                                                if (app.activityStack[i] !is MainActivity) {
                                                    app.activityStack[i].finish()
                                                }
                                            }
                                            finish()
                                        }
                                        wechatRecharge(
                                            response?.appid,
                                            response?.noncestr,
                                            response?.`package`,
                                            response?.partnerid,
                                            response?.prepayid,
                                            response?.sign,
                                            response?.timestamp
                                        )
                                    }

                                    override fun onError(e: APIException) {
                                        tipFail(e.eMessage)
                                    }

                                })
                            }

                            override fun onError(e: APIException) {
                                tipFail(e.eMessage)
                            }

                        })

                    }
                    1 -> {
                        lifecycleScope.request({
                            APIMemberApps.service().recharg(edit_phone.text.toString().toInt())
                        }, object : BaseAPI<RechargeEntity>() {
                            override fun onSuccess(request: RechargeEntity?, state: Int, msg: String) {
                                lifecycleScope.request({
                                    APIPay.service().alipay(
                                        request?.order_code ?: "",
                                        "6"
                                    )
                                }, object : BaseAPI<AlipayEntity>() {
                                    override fun onSuccess(
                                        t: AlipayEntity?,
                                        state: Int,
                                        msg: String
                                    ) {
                                        AliPay(activity).pay(
                                            t?.order_string ?: "",
                                            "6",
                                            request?.order_code ?: "",
                                        0.00,0)
                                    }

                                    override fun onError(e: APIException) {
                                        tipFail(e.eMessage)
                                    }

                                })
                            }

                            override fun onError(e: APIException) {
                                tipFail(e.eMessage)
                            }

                        })

                    }
                }
        }
    }

    private fun wechatRecharge(
        appid: String?,
        noncestr: String?,
        `package`: String?,
        partnerid: String?,
        prepayid: String?,
        sign: String?,
        timestamp: String?
    ) {
        if (appid == null || noncestr == null || `package` == null || partnerid == null
            || prepayid == null || sign == null || timestamp == null
        ) {
            tipWarn("支付环境异常")
            return
        }
        val msgApi = WXAPIFactory.createWXAPI(context, null)
        msgApi.registerApp(appid)
        val request = PayReq().apply {
            this.appId = appid
            this.nonceStr = noncestr
            this.packageValue = `package`
            this.partnerId = partnerid
            this.prepayId = prepayid
            this.sign = sign
            this.timeStamp = timestamp
        }
        msgApi.sendReq(request)
    }

    class Adapter : BaseQuickAdapter<PayTypeEntity, BaseViewHolder>(R.layout.item_pay_type) {
        var position = -1
        override fun convert(helper: BaseViewHolder, item: PayTypeEntity) {
            helper.getView<SmoothCheckBox>(R.id.check_box)
                .setChecked(position == helper.layoutPosition - headerLayoutCount, true)
            helper.setImageResource(R.id.iv_pay_type, item.drawableInt)
                .setText(R.id.tv_pay_type_name, item.name)
                .setText(R.id.tv_pay_type_money, item.money)
        }

    }
}